package com.guo.todo.usercenter.service.credential.impl;

import com.guo.todo.common.cache.CacheUtil;
import com.guo.todo.common.credential.Credential;
import com.guo.todo.common.excepiton.CommonException;
import com.guo.todo.common.util.EncryptUtil;
import com.guo.todo.usercenter.dao.ProfileMapper;
import com.guo.todo.usercenter.domain.Profile;
import com.guo.todo.usercenter.domain.ProfileExample;
import com.guo.todo.usercenter.service.credential.CredentialService;
import com.guo.todo.usercenter.service.session.SessionService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Auther: hotlove_linx
 * @Date: 2023/7/19 22:31
 * @Description:
 */
@Service
public class CredentialServiceImpl implements CredentialService {

    @Resource(name = "redisSessionService")
    private SessionService sessionService;

    @Resource
    private ProfileMapper profileMapper;


    @Override
    public Credential loginProfile(String profileName, String password, int terminal) throws CommonException {

        ProfileExample profileExample = new ProfileExample();
        profileExample.createCriteria().andNameEqualTo(profileName)
                .andPasswordEqualTo(password);

        List<Profile> profiles = profileMapper.selectByExample(profileExample);

        if (CollectionUtils.isEmpty(profiles)) {
            throw new CommonException("用户名或密码错误");
        }

        Profile profile = profiles.get(0);

        Credential credential = new Credential();
        credential.setProfileId(profile.getId());
        credential.setAvatarUrl(profile.getAvatarUrl());
        credential.setProfileName(profile.getName());
        credential.setTerminal(terminal);

        // 生成token 并保存用户信息
        sessionService.createSession(credential);

        return credential;
    }

    @Override
    public void validSession(String token, int terminal) throws CommonException {
        Credential credential = new Credential();
        credential.setToken(token);
        credential.setTerminal(terminal);
        sessionService.validAndFreshSession(credential);
    }
}
